package org.kwin.springboot;

import org.kwin.spring.util.FilePath;
import org.kwin.spring.web.DispatchServlet;
import org.kwin.springboot.tomcat.ServletAndParrern;
import org.kwin.springboot.tomcat.TomcatServer;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author : wangkai
 * @version V1.0
 * @Package org.kwin.springboot
 * @Description:
 * @date 2021年10月08日 17:32
 **/
public class SpringApplication {
    
    public static void run(Class<?> clazz, String[] args)
    {
        // 获取配置文件
        Properties properties = new Properties();
//        SpringApplication.
//        InputStream inputStream = SpringApplication.class.getResourceAsStream("application.properties");
/*        File file1 = new File("spring\\src\\main\\resources\\application.properties");
        if(!file1.exists()) {
            System.out.println("dosen");
        }
        if(file1.isDirectory()) {
            System.out.println("dir");
        }
        if(file1.isFile()) {
            System.out.println("file");
        }*/
        File file = new File(FilePath.RESOURCES_PATH + "application.properties");
        if (!file.exists())
        {
            System.err.println("找不到myspringboot配置文件");
            return;
        }
        try
        {
            properties.load(new FileInputStream(file));
        } catch (Exception e)
        {
            System.err.println("访问myspringboot配置文件出现错误");
            e.printStackTrace();
        }
        run(properties, clazz);
    }
    
    private static void run(Properties properties, Class<?> calzz)
    {
        // 首页配置Servlet
//        ServletAndParrern indexServlet = new ServletAndParrern(new IndexServlet(properties));
//        // 静态资源Servlet
//        ServletAndParrern staticServlet = new ServletAndParrern(new StaticServlet());
//        // 模版页面Servlet
//        ServletAndParrern templatesServlet=new ServletAndParrern(new TemplatesServlet());
        // SpringMVC
        ServletAndParrern dispatchServlet = new ServletAndParrern(new DispatchServlet(calzz,properties));
        
        List<ServletAndParrern> list = new ArrayList<>();
//        list.add(indexServlet);
//        list.add(staticServlet);
//        list.add(templatesServlet);
        list.add(dispatchServlet);
        int port = 8080;
        if (properties.containsKey("port"))
        {
            try
            {
                port = Integer.parseInt(properties.getProperty("port"));
            } catch (Exception e)
            {
                System.err.println("配置项：port，必须是整数类型");
                e.printStackTrace();
            }
        }
        // 启动servlet容器
        TomcatServer.start("", list, port);
    }
}
